<template>
  <div
    :style="'height: ' + innerHeight + 'px'"
    v-loading="loading"
    element-loading-text="页面正在加载中..."
    element-loading-background="rgba(0, 0, 0, 0.8)"
    :element-loading-lock="true"
  >
    <!--分页组件-->
    <pager
      :tbcols="tbcols"
      :tbdata="tbdata"
      :Pagination="Pagination"
      :reloadPagerData="reloadPagerData"
      ref="tbpager"
    >
      <template #serchInner>
        <el-form label-width="120px" :model="editData">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="配件编号">
                <el-input v-model="serchParam.pidLike"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="配件名称">
                <el-input v-model="serchParam.pnameLike"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="车型">
                <el-input v-model="serchParam.chexingLike"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备注">
                <el-input v-model="serchParam.beizhuLike"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #tbColSlot>
        <template v-if="bthide">
          <el-table-column label="设置" width="120">
            <template #default="scope">
              <el-button type="primary" size="small" @click="tbSelectbt(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </template>
      </template>
      <!--分页控件标题区域-->
      <template #soltTitle> 配件资料管理 </template>
      <!--表格操作按钮区域  以具名插槽的方式使用-->
      <template #slotBts>
        <!--
      <el-button type="primary" @click="getSelectRow">选择</el-button>
      <el-button type="info">编辑</el-button>      
      
        <el-button type="success" @click="add">新建</el-button>
        <el-button type="danger" @click="stop">禁用/启用</el-button>
      -->
        <template v-for="(item, index) in buttons" :key="index">
          <template v-if="item.value == 'Search'">
            <el-button
              @click="reloadPagerData"
              :style="'color:#000;background-color:' + item.color + ';'"
              >查询</el-button
            >
          </template>
          <template v-else>
            <el-button
              v-if="!bthide"
              @click="methodUtils(item.value)"
              :style="'color:#fff;background-color:' + item.color + ';'"
              >{{ item.name }}</el-button
            >
          </template>
        </template>
      </template>
    </pager>

    <!--弹窗控件-->
    <detail ref="mx" :detailSave="detailSave">
      <template #content>
        <div :style="'height: ' + mxHeight + 'px'">
          <el-form label-width="120px" :model="editData">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="配件编号">
                  <el-input v-model="editData.pid"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="配件名称">
                  <el-input v-model="editData.pname"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="车型">
                  <el-input v-model="editData.chexing"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="销售价">
                  <el-input
                    v-model="editData.xiaoshoujia"
                    oninput="value=value.replace(/[^0-9.]/g,'')"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="备注">
                  <el-input v-model="editData.beizhu"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
    </detail>
  </div>
</template>
<script lang="ts" setup name="miyaouser">
import http from '@/api/http'
import { onMounted, ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import pager from '@/components/zjc/pager.vue'
import detail from '@/components/zjc/details.vue'
import { type Paginations } from '@/model/pagination.ts'
import store from '@/store/index.js'
import { useRoute } from 'vue-router'
import permission from '@/api/zjc/zjcpermission.js'

let serchParam = reactive({ pidLike: null, pnameLike: null, chexingLike: null, beizhuLike: null })
const buttons = reactive([])
const mx = ref()
const tbpager = ref(null)
const editData = reactive({ UserName: null })

const loading = ref(false)
const innerHeight = ref(window.innerHeight - 140)

const mxHeight = ref(innerHeight.value * 0.7)

const dialogVisible_Zhanghao = ref(false)

const selectZhanghao = () => {
  dialogVisible_Zhanghao.value = true
}

//页面初始化加载完成钩子
onMounted(async () => {
  //获取当前页面路由
  const route = useRoute()
  //alert(route.path);
  //获取缓存中的权限信息
  let store_permission = store.getters.getPermission(route.path)
  //alert(JSON.stringify(store_permission));
  //在权限信息中获取按钮
  var permissionButtons = permission.getButtons(route.path)
  if (permissionButtons) {
    //2020.03.31添加深拷贝按钮组
    permissionButtons.forEach((p) => {
      let _obj = {}
      for (const key in p) {
        _obj[key] = p[key]
      }
      buttons.push(_obj)
    })
    // this.buttons.push(...permissionButtons);
  }
  //alert(JSON.stringify(buttons))

  await reloadPagerData(Pagination)
})

//定义分页参数
let Pagination: Paginations = reactive({
  Sort: 'CreateDate',
  SortType: ' desc ',
  PageIndex: 1,
  PageSize: 5,
  TotalCount: 0
})
//定义表格列的信息
let tbcols: any[] = [
  { prop: 'pid', label: '配件编号', width: 220, align: 'center' },
  { prop: 'pname', label: '配件名称', width: 250, align: 'center' },
  { prop: 'chexing', label: '车型', width: 300, align: 'left' },
  { prop: 'xiaoshoujia', label: '销售价', width: 180, align: 'center' },
  { prop: 'beizhu', label: '备注', width: null, align: 'center' }
]
//定义表格数据
let tbdata: any[] = reactive([])

//获取选中行
/**
 * vue3 语法糖的方法中没法直接使用this.$refs
 * 解决方案：定义一个变量，并且变量的名字和要获取数据的子组件的ref的名字一致
 * 然后使用变量名.value.子组件中的方法名或变量名 即可调用子组件中的数据。
 * 注意子组件中调用的数据需要对外暴漏：defineExpose({dataonLineListSelections});
 */
const getSelectRow = () => {
  let selectRowsData = tbpager.value.dataonLineListSelections
  //alert(JSON.stringify(selectRowsData))
  return selectRowsData
}

const clearSelectRow = async () => {
  await reloadPagerData(Pagination)
}

//重新执行分页
const reloadPagerData = async (Pagination: Paginations) => {
  loading.value = true
  await loadData().then((res) => {
    tbdata.splice(0, tbdata.length)
    tbdata.push(...res)
    loading.value = false
  })
}

async function loadData() {
  //第一步：加载分页数据
  const arr = await loadPagerData()
  //第二步：追加分页数据属性
  /*
  var i = 0
  for (i = 0; i < arr.length; i++) {
    var item = arr[i]
    Object.assign(arr[i], {
      DisableUseValue: item.DisableUse == 1 ? '否' : '是',
      UserName: await GetColValueByKey('sys_user', 'UserName', 'User_Id', item.UserId)
    })
  }*/
  return arr
}

async function loadPagerData() {
  const arr = []
  const res = await http.get('api/qx_peijian/GetPageDataZjc', {}, false, {
    params: Object.assign(Pagination, serchParam)
  })
  if (res.Tag == 1) {
    //alert(JSON.stringify(res.Data));
    arr.push(...res.Data)
    Pagination.TotalCount = res.Total
  } else {
    ElMessage({
      message: '系统异常，操作失败！',
      type: 'error'
    })
  }
  return arr
}

async function GetColValueByKey(
  tableName: string,
  selectColName: string,
  whereKey: string,
  whereKeyValue: string
) {
  /**
   * 这里注意 第三个参数一定要设置为false
   * 设置为false即关闭loading动画加载效果
   * 设置它为false就会避免页面在加载的时候不断的闪烁
   */
  const result = await http.get('api/sys/GetColValueByKey', {}, false, {
    params: {
      tableName: tableName,
      selectColName: selectColName,
      whereKey: whereKey,
      whereKeyValue: whereKeyValue
    }
  })
  return result
}

//增删改查方法综合调度
const methodUtils = async (category) => {
  //alert(category)
  if (category == 'Add') {
    await addOrUpdOpen('00000000-0000-0000-0000-000000000000')
  } else if (category == 'DisableUse') {
    stop()
  } else if (category == 'Delete') {
    del()
  } else if (category == 'Update') {
    let selectRowsData = tbpager.value.dataonLineListSelections
    if (selectRowsData.length != 1) {
      ElMessage({
        message: '只能选择至少1行数据！',
        type: 'error'
      })
      return
    }
    await addOrUpdOpen(selectRowsData[0].Id)
  }
}

//添加或修改信息
const addOrUpdOpen = async (id) => {
  await http
    .get('api/qx_peijian/GetObjectJson', {}, false, {
      params: { Id: id }
    })
    .then(async (res) => {
      Object.assign(editData, res.Data)
      let title_a = '修改配件资料'
      //新增初始化
      if (editData.Miyao_Id == '00000000-0000-0000-0000-000000000000') {
        title_a = '添加配件资料'
      } else {
      }
      mx.value.loadPage(title_a, '90%')
      //alert(JSON.stringify(editData));
    })
}

//用户删除
const del = async () => {
  let selectRowsData = tbpager.value.dataonLineListSelections
  if (selectRowsData.length != 1) {
    ElMessage({
      message: '只能选择至少1行数据！',
      type: 'error'
    })
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 删除操作
    const res = await http.get('api/qx_peijian/DeleteFromJson', {}, true, {
      params: {
        id: selectRowsData[0].Id
      }
    })

    if (res.Tag == 1) {
      ElMessage({
        message: '数据删除成功!',
        type: 'success'
      })
      await reloadPagerData(Pagination)
    } else {
      ElMessage({
        message: '系统错误，操作失败！',
        type: 'error'
      })
    }
  } catch (err) {
    // 用户取消了删除
    //console.log('取消了删除');
  }
}

//禁用与开启
const stop = async () => {
  let selectRowsData = tbpager.value.dataonLineListSelections
  if (selectRowsData.length != 1) {
    ElMessage({
      message: '只能选择至少1行数据！',
      type: 'error'
    })
    return
  }

  const res = await http.get('api/miyaouser/StopFormJson', {}, true, {
    params: {
      Miyao_Id: selectRowsData[0].Miyao_Id
    }
  })

  if (res.Tag == 1) {
    ElMessage({
      message: '操作成功，该用户已被禁用或启用!',
      type: 'success'
    })
    await reloadPagerData(Pagination)
  } else {
    ElMessage({
      message: '系统错误，操作失败！',
      type: 'error'
    })
  }
}

//明细保存
const detailSave = async () => {
  //alert(JSON.stringify(editData));
  const res = await http.post('api/qx_peijian/SaveFormJson', editData, true)
  if (res.Tag == 1) {
    ElMessage({
      message: '操作成功！',
      type: 'success'
    })
    mx.value.dialogVisible = false
    await reloadPagerData(Pagination)
  } else {
    ElMessage({
      message: res.Message,
      type: 'error'
    })
  }
}

defineExpose({ getSelectRow, clearSelectRow })

const props = defineProps({
  bthide: Boolean,
  tbSelectbt: Function
})

//let props = defineProps(['bthide','tbSelectbt']);
</script>

<style scoped>


</style>
